const mongoose = require('mongoose')
const moment = require('moment')
const _ = require('lodash')
const thunkify = require('thunkify')
const helper = require('../modules/helper')

// Plugging in your own Promises Library
// Use native promises
mongoose.Promise = global.Promise

const Schema = mongoose.Schema

const field = {
  _id: 1, ip: 1, created_at: 1, order: 1, product: 1,
  seller_id: 1, browser: 1, district: 1, url: 1,
}

let vistorSchema = new Schema({
  referrer_url: String,
  url: String,
  ip: String,
  district: String,
  user_agent: String,
  browser: Schema.Types.Mixed,
  equipment: String,
  product: Schema.Types.Mixed,
  order: Schema.Types.Mixed,
  seller_id: String,
  user: String,
  created_at: String,
})

let Vistor = mongoose.model('Vistor', vistorSchema)

function format(body, Vistor) {
  return new Vistor({
    referrer_url: body.referrer_url,
    url: body.url,
    ip: body.ip,
    district: body.district,
    user_agent: body.user_agent,
    browser: body.browser,
    equipment: body.equipment,
    product: body.product,
    order: body.order,
    seller_id: body.seller_id,
    user: body.user_id,
    created_at: (new Date()).toLocaleString(),
  })
}

Vistor.create = function(valueObj) {
  return format(valueObj, this).save()
}

Vistor.findByRegex = function(flag, pattern, sellerId, done) {
  const query = this.where('created_at').regex(pattern)

  if (sellerId !== null) {
    query.or([
      {seller_id: sellerId},
      {'product.seller_id': sellerId},
      {'order.seller_id': sellerId},
    ])
  }

  return query.select(field).exec()
}

// TypeError: this.where is not a function
// this === exports true
// Vistor.findByRange = (flag, createdAtRange, sellerId) => {
Vistor.findByRange = function(flag, createdAtRange, sellerId, done) {
  const query = this.where('created_at')
    .gte(createdAtRange.start + ' 00:00:00')
    .lte(createdAtRange.end + ' 23:59:59')

  if (sellerId !== null) {
    query.or([
      {seller_id: sellerId},
      {'product.seller_id': sellerId},
      {'order.seller_id': sellerId},
    ])
  }

  // with no `return` there will be a error triggered
  // yield `undefined` error
  return query.select(field).exec()
}

// with generator `yield`
Vistor.findPageDurationTimeByRegex = function* (pattern) {
  const docs = yield this.where('created_at').regex(pattern)
    .select(field)
    .exec()

  let outputArr = []
  for (let doc of docs) {
    let condition = {
      referrer_url: doc.url,
      created_at: {
        $gt: doc.created_at,
        $lte: moment(doc.created_at).add(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
      },
    }
    const result = yield this.findOne(condition)
      .select({ referrer_url: 1, created_at: 1 })
      .exec()
    if (result) {
      let end = (new Date(result.created_at)).getTime() / 1000
      let start = (new Date(doc.created_at)).getTime() / 1000
      let duration = end - start
      let obj = {}
      obj[doc.url] = duration
      outputArr.push(obj)
    }
    else {
      outputArr.push(0)
    }
  }
  return _.remove(outputArr, (val) => {
    return val != 0
  })
}

module.exports = Vistor
